package com.dobby.logger.system.aop;

import com.dobby.logger.system.vo.SystemLog;
import com.dobby.logger.utils.BrowserUtils;
import com.dobby.logger.utils.CommonUtils;
import com.dobby.logger.utils.DateFormatUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created by liguoqing on 2016/3/7.
 */
@Aspect
@Component
public class SystemLogAspect {

    @Autowired
    private AsynAddLogHandler asynAddLogHandler;

    private  static  final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);


    @Pointcut("execution(* com.dobby.logger.business..*.*(..)) ")
    public void log() {
        logger.info("我是一个切入点..." + new Date());
    }

    /**
     * 方法调用前执行
     * @param joinPoint
     * @throws Exception
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Exception {
        logger.info("方法调用前执行..." + new Date());
        saveToCassandraAndSolr(joinPoint, null);
    }

    /**
     * 标注该方法体为异常通知，当目标方法出现异常时，执行该方法体
     */
    @AfterThrowing(pointcut = "log()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        logger.info("出现异常时执行..." + new Date());
        saveToCassandraAndSolr(joinPoint, e);
    }


    /**
     * 存储日志到solr和cassandra
     * @param joinPoint
     * @param e
     */
    private void saveToCassandraAndSolr(JoinPoint joinPoint, Throwable e) {
        logger.info(joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName() + "()");

        // 获取信息
        String params = "[";
        Object[] arguments = joinPoint.getArgs();
        for (int i = 0; i < arguments.length; i++) {
            if(arguments[i] != null && !arguments[i].equals("")) {
                params += arguments[i] + ",";
            }
        }
        if(params.contains(",")) {
            params = params.substring(0,params.length()-1) + "]";
        } else {
            params = params + "]";
        }
        String ipAddress = "";
        String url = "";
        String broswer = "";
        if(RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ipAddress = request.getRemoteAddr();
            if("0:0:0:0:0:0:0:1".equals(ipAddress)){
                ipAddress = "127.0.0.1";
            }
            HttpSession session = request.getSession();
            broswer = BrowserUtils.checkBrowse(request);
            url = request.getRequestURL().toString();
        }

        SystemLog systemLog = new SystemLog();
        systemLog.setId(CommonUtils.getUUID());
        systemLog.setIpAddress(ipAddress);
        systemLog.setBroswer(broswer);
        systemLog.setOperateDate(DateFormatUtils.getSolrFormatStr(new Date()));
        systemLog.setUrl(url);
        systemLog.setMethodName(joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName() + "()");
        systemLog.setParams(params);
        if(e != null) {
            systemLog.setExceptionMsg(e.getClass().getName());
        } else {
            systemLog.setExceptionMsg("");
        }

        systemLog.setCompanyId("lgq");
        systemLog.setUserId("lgq");
        asynAddLogHandler.addSysLog(systemLog);
    }


}
